package api

import (
	"errors"
	"go_web/common"
	"go_web/dao"
	"go_web/models"
	"go_web/service"
	"go_web/utils"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func (a *Api) GetPost(w http.ResponseWriter, r *http.Request) {

	path := r.URL.Path

	pIdStr := strings.TrimPrefix(path, "/api/v1/post/")

	pId, err := strconv.Atoi(pIdStr)
	if err != nil {
		common.Error(w, errors.New("路径请求错误"))
		return
	}

	post, err := dao.GetPostDetailByPId(pId)
	if err != nil {
		common.Error(w, errors.New("数据加载失败"))
		return
	}

	common.Success(w, post)

}

func (a *Api) SaveAndUpdatePost(w http.ResponseWriter, r *http.Request) {
	//获取用户ID
	token := r.Header.Get("Authorization")

	_, claims, err := utils.ParseToken(token)
	if err != nil {
		common.Error(w, errors.New("登录过期"))
		return
	}

	uid := claims.Uid

	method := r.Method
	switch method {
	case http.MethodPost:
		//post save
		params := common.GetRequestJSONParam(r)
		cId := params["categoryId"].(string)
		content := params["content"].(string)
		markdown := params["markdown"].(string)
		slug := params["slug"].(string)
		title := params["title"].(string)
		postType := params["type"].(float64)
		pType := int(postType)

		category, _ := strconv.Atoi(cId)

		post := &models.Post{
			Title:      title,
			Content:    content,
			Slug:       slug,
			Markdown:   markdown,
			Type:       pType,
			UserId:     uid,
			ViewCount:  1,
			CreateAt:   time.Now(),
			UpdateAt:   time.Now(),
			CategoryId: category,
		}

		service.SavePost(post)
		common.Success(w, post)

	case http.MethodPut:
		//put update
		params := common.GetRequestJSONParam(r)
		cId := params["categoryId"].(string)
		content := params["content"].(string)
		markdown := params["markdown"].(string)
		slug := params["slug"].(string)
		title := params["title"].(string)
		postType := params["type"].(float64)
		pidFloat := params["pid"].(float64)
		pType := int(postType)
		pid := int(pidFloat)

		category, _ := strconv.Atoi(cId)

		post := &models.Post{
			Title:      title,
			Content:    content,
			Slug:       slug,
			Markdown:   markdown,
			Type:       pType,
			UserId:     uid,
			ViewCount:  1,
			CreateAt:   time.Now(),
			UpdateAt:   time.Now(),
			CategoryId: category,
			Pid:        pid,
		}

		service.UpdatePost(post)
		common.Success(w, post)
	}

}
func (a *Api) SearchPost(w http.ResponseWriter, r *http.Request) {

	_ = r.ParseForm()
	condition := r.Form.Get("val")

	searchResps, err := service.SearchPost(condition)
	if err != nil {
		log.Println(err)
	}

	common.Success(w, searchResps)

}
